import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:hairen_app/server/server.dart';
import '../player/player.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class SearchPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new SearchPageState();
  }
}

class SearchPageState extends State<SearchPage> {
  TextEditingController _textController=new TextEditingController();

  ScrollController _scrollController = new ScrollController();
  bool downType = true;
  bool isLoading = false;
  bool stopLoading = false;


  bool isSearch=false;
  bool isGetSearch=false; //获取搜索状态
  var searchHotList=[];
  int last_page=0;
  int current_page=0;
  String searchName="";
  
  bool isList=true; //是否搜素到


  int curPage = 0;
  List<Map> searchList = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textController.addListener((){
      searchName=_textController.text.toString();
      setState(() {
        if (searchName.length > 0) {
            isSearch = true;
            stopLoading = false;
            current_page = 0;
            searchList=[];
            getSearch(searchName);
        } else {
          isSearch = false;
        }
      });
    });


    //监听下拉加载更多
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (!isLoading) {
          setState(() {
            this.isLoading = true;
          });
          getSearch(searchName);
        }
      }
    });
    //搜索关键字


    //获取搜索热门
    Server.getUpSearch().then((ret){
      setState(() {
        searchHotList=ret['data']['data'];
      });
    });


  }


  getSearch(String val){


    print("zhangt:${stopLoading}");
    print("page:${current_page}");
    print("var:${val}");
    if(!stopLoading){
      current_page+=1;
      Server.getSearchMoves(data: {"name": val,"page":current_page.toString(),}).then((ret) {
        print(ret['data']['last_page'].runtimeType);

        setState(() {
          last_page=ret['data']['last_page'];
          current_page=ret['data']['current_page'];

          List data=ret['data']['data'];
          isList=data.isEmpty;
          if(current_page>last_page){
            stopLoading=true;
          }
          
          for(var i=0;i<data.length;i++){
            searchList.add(data[i]);
          }
          this.isLoading = false;
        });

      });
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _textController.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
          elevation: 0.0,
          title: new Container(
            height: 35.0,
            padding: EdgeInsets.only(left: 10.0, right: 10.0),
            alignment: Alignment.center,
            decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: new BorderRadius.all(Radius.circular(5.0))),
            child: new TextField(
                controller:_textController,
              style: new TextStyle(color: Colors.black),
              decoration: new InputDecoration(
                contentPadding: const EdgeInsets.only(top: 0.0),
                hintText: "请输入你想搜索的电影",
//                fillColor: Colors.white,
//              InputBorder: new OutlineInputBorder(),
                border: InputBorder.none,
              ),
            ),
          ),
          actions: <Widget>[
            new Container(
              child: !isSearch?IconButton(icon: Icon(Icons.search), onPressed: () {},color:Colors.white):IconButton(icon: Icon(Icons.close), onPressed: () {
                isSearch=false;
                isList=false;
                _textController.clear();
              },color:Colors.white),
            ),
            new SizedBox(width: 10.0,)
          ]),
      body:new ListView(
        controller: _scrollController,
        children: <Widget>[
          new Offstage(
            child:  new Container(
                padding: EdgeInsets.all(10.0),
                child:new Column(
                  children: <Widget>[
                    new Container(
                      height: 40.0,
                      padding: EdgeInsets.only(left: 10.0),
                      child: new Row(
                        children: <Widget>[
//                      new Icon(Icons.search),
                          new Text('热门搜索',style: new TextStyle(color:Color.fromRGBO(251, 114, 153, 1.0)))
                        ],
                      ),
                    ),
                    new Wrap(
                      spacing: 10.0, // gap between adjacent chips
                      runSpacing: 10.0, // gap between lines
                      children: searchHotList.map((item){
                        return    new Chip(
                          avatar: new CircleAvatar(backgroundColor:Color.fromRGBO(251, 114, 153, 1.0), child: new Text('H',style: new TextStyle(color: Colors.white))),
                          label: new Text('${item['title']}'),
                        );
                      }).toList(),
                    ),
                  ],
                )
            ),
            offstage:isSearch ,
          ),
          isList?new Container(
            padding: EdgeInsets.only(top: 20.0),
            alignment: Alignment.center,
            child: new Text('没有搜索到内容',style: new TextStyle(fontSize: 16.0),),
          ):new Offstage(
            child: searchList.length>0?new Column(
              children: searchList.map((item){
                return   new ListTile(
                  leading:new Container(
                    padding: EdgeInsets.only(left: 10.0,right: 10.0,top: 3.0,bottom: 3.0),
                    child: new Text('${item['type']}',style: new TextStyle(color: Colors.white),),
                    decoration: new BoxDecoration(
                        color:  Color.fromRGBO(251, 114, 153, 1.0),
                        borderRadius: new BorderRadius.all(Radius.circular(5.0))
                    ),
                  ),
                  title: new Text('${item['title']} '),
                  onTap: (){
                    //搜索次数
                    Server.updateHot(data: {"id":item['id'].toString()}).then((ret){
                    });
                    Navigator.of(context).push(
                        new CupertinoPageRoute(builder: (context)=>new PlayerPage(mid:int.parse(item['id'])))
                    );
                  },
                );
              }).toList()
            ):new Container(
            height: 100.0,
            child: new SpinKitWave(
            color: Color.fromRGBO(251, 114, 153, 1.0),
            size: 30.0,
            )),
            offstage:!isSearch ,
          ),
          new Offstage(
            offstage:!isLoading,
            child:  new SpinKitWave(
              color: Color.fromRGBO(251, 114, 153, 1.0),
              size: 30.0,
            ) ,
          )
        ],
      ),
    );
  }
}
